class Node {
    constructor(key = 0, value = 0) {
        this.key = key;
        this.value = value;
        this.next = null;
        this.prev = null;
    }
}

class LRUCache {
    constructor(capacity) {
        this.capacity = capacity;
        this.cache = new Map(); // 缓存
        this.dummy = new Node();
        this.dummy.prev = this.dummy;
        this.dummy.next = this.dummy;
    }

    getNode(key) {
        if (!this.cache.has(key))
            return null;
        const node = this.cache.get(key);
        this.remove(node);
        this.moveToHead(node);
        return node;
    }

    get(key) {
        const node = getNode(key);
        return node === null ? -1 : node.value;
    }

    put(key, value) {
        let node = this.cache.get(key);
        if (node) {
            node.value = value;
            return;
        }
        node = new Node(key, value);
        this.cache.set(key, node);
        this.moveToHead(node);
        if (this.cache.size > this.capacity) {
            const delNode = this.dummy.prev;
            this.cache.delete(delNode.key);
            this.remove(delNode);
        }
    }

    remove(node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }

    moveToHead(node) {
        node.prev = this.dummy;
        node.next = this.dummy.next;
        node.prev.next = node;
        node.next.prev = node;
    }
}